import {RouteRecordRaw} from 'vue-router'
import type {UserRoute} from '@/type/user'

const viewData: {[key: string]: any} = import.meta.glob('@/view/**/*.vue')

const toCamelCase = (value: string, upperCaseFirst: boolean) => {
    value = (value || '')
        .replace(/\/(.)/g, function(group: string) {
            return group.toUpperCase()
        })
        .replaceAll('/', '')

    if (upperCaseFirst && value) {
        value = value.charAt(0).toUpperCase() + value.slice(1)
    }
    return value
}

/**
 * 组装用户路由树
 */
export const generateTree = (list: Array<UserRoute>, filter?: (item: UserRoute) => boolean): Array<UserRoute> => {
    list = JSON.parse(JSON.stringify(list))
    if (filter) {
        list = list.filter(filter)
    }
    let _map: Map<string, UserRoute> = list.reduce((map: Map<string, UserRoute>, item: UserRoute) => {
        map.set(item.identity, item)
        return map
    }, new Map<string, UserRoute>())

    list.forEach((item: UserRoute) => {
        let parent: UserRoute | undefined = _map.get(item.parent)
        let current: UserRoute | undefined = _map.get(item.identity)
        if (parent) {
            if (!parent?.children) {
                parent.children = []
            }
            if (current) {
                parent.children.push(current)
            }
            _map.set(item.parent, parent)
        }
    })
    return list.filter((item: UserRoute): boolean => item.parent == '0')
}

/**
 * 后端控制路由生成
 */
export const generateRoute = (list: Array<UserRoute>): Array<RouteRecordRaw> => {
    list = JSON.parse(JSON.stringify(list))
    list = list.filter(item => item.type == 2)
    let routeList: Array<RouteRecordRaw> = []
    for (const route of list) {
        // 路由地址转首字母大写驼峰, 作为路由名称
        let data: RouteRecordRaw = {
            path: route?.path || '',
            meta: {
                title: route?.name || ''
            },
            children: [],
            name: (route?.path || '').length > 0 ? toCamelCase(route.path, true) : ''
        }
        if (route.path && route.type == 2) {
            let key: string = `/src/view/${route.path}.vue`.replace('//', '/')
            data.component = viewData[key]
            routeList.push(data)
        }
    }
    return routeList
}
